package com.yx.listener;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.yx.constatns.RabbitMQConstatns;
import com.yx.entity.Order;
import com.yx.entity.OrderDetail;
import com.yx.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Classname OrderListener
 * @Date 2021/07/26 21:29
 * @Author by yx
 * @Description TODO:
 */
@Component
@Slf4j
public class OrderListener {

    @Autowired
    private IOrderService orderService;

    @RabbitListener(queues = RabbitMQConstatns.ORDER_DLE_QUEUE)
    public void orderUpdateStatus(String json, Channel channel, Message message){
        //1.获取routingkey
        String routingKey = message.getMessageProperties().getReceivedRoutingKey();
        log.debug("{}", json);
        Map dleMap = JSON.parseObject(json, Map.class);
        switch (routingKey) {
            case "dle.order.err":
                // 业务处理
                log.debug("延迟队列进来了");
                String string = JSON.toJSONString(dleMap.get("orderDetailList"));
                List<OrderDetail> orderDetailList = JSON.parseArray(string, OrderDetail.class);
                Map<String,Object> orderMap = (Map<String, Object>) dleMap.get("order");
                Order order = JSON.parseObject(JSON.toJSONString(orderMap), Order.class);
                // 根据oid查询订单状态
                Order orderByOid = orderService.getOrderByOid(order.getOid());
                // 根据订单状态,执行不同的
                switch (orderByOid.getStatus()){
                    case 1: // 未支付
                        log.debug("1m了,订单状态为未支付,修改订单状态为超时");
                        orderService.updateOrderStatus(order.getOid(), 4);
                        // 释放库存???由死信队列来完成
                        break;
                    case 2: //已支付, 不执行操作
                        log.debug("订单已支付,不需要处理");
                        break;
                    case 3: // 已取消
                        log.debug("订单取消");
                    default:
                        break;
                }
                try {
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            default:
                System.out.println("无此routingKey");
                break;
        }
    }
}
